package cn.edu.buu.hospital.web;

import cn.edu.buu.hospital.entity.Appointment;
import cn.edu.buu.hospital.entity.Pay;
import cn.edu.buu.hospital.entity.Report;
import cn.edu.buu.hospital.entity.User;
import cn.edu.buu.hospital.service.AppointmentService;
import cn.edu.buu.hospital.service.PayService;
import cn.edu.buu.hospital.service.ReportService;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 支付控制器
 */
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpSession;

@Controller
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private PayService payService;
    
    @Autowired
    private AppointmentService appointmentService;
    
    @Autowired
    private ReportService reportService;

    // 跳转到新增支付页面
    @GetMapping("/toAdd")
    public String toAdd() {
        return "backend/pay/add";
    }

    // 新增支付
    @PostMapping("/add")
    public String add(Pay pay, Model model) {
        try {
            payService.add(pay);
            return "redirect:find";
        } catch (Exception e) {
            model.addAttribute("error", "新增失败: " + e.getMessage());
            model.addAttribute("pay", pay);
            return "backend/pay/add";
        }
    }

    // 查询支付列表
    @RequestMapping(value = "/find", method = {RequestMethod.GET, RequestMethod.POST})
    public String find(Model model,
                       @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                       @RequestParam(value = "patientName", required = false) String patientName,
                       @RequestParam(value = "status", required = false) Integer status,
                       @RequestParam(value = "payDate", required = false) String payDate,
                       HttpSession session) {
        int pageSize = 5;
        // 创建查询条件对象
        Pay condition = new Pay();
        if (status != null) {
            condition.setPaystatus(status);
        }

        // 从session中获取当前登录用户信息
        User loginUser = (User) session.getAttribute("loginAdmin");

        // 如果是病人用户(type=1)，则只能查看自己的支付记录
        if (loginUser != null && loginUser.getType() == 1) {
            // 使用新添加的findByUserId方法查询用户的支付记录
            PageInfo<Pay> pageInfo = payService.findByUserId(pageNum, pageSize, loginUser.getUserid(), condition, payDate);
            model.addAttribute("pageInfo", pageInfo);
            model.addAttribute("patientName", loginUser.getUsername());
            model.addAttribute("status", status);
            model.addAttribute("payDate", payDate);
            model.addAttribute("loginUser", loginUser);
            return "backend/pay/list";
        }

        // 非病人用户可以按患者姓名搜索
        if (patientName != null && !patientName.isEmpty()) {
            Appointment appointment = new Appointment();
            appointment.setPatientName(patientName);
            condition.setAppointment(appointment);
        }

        PageInfo<Pay> pageInfo = payService.find(pageNum, pageSize, condition, payDate);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("patientName", patientName);
        model.addAttribute("status", status);
        model.addAttribute("payDate", payDate);
        model.addAttribute("loginUser", loginUser);
        return "backend/pay/list";
    }

    // 根据ID查询支付（用于编辑）
    @GetMapping("/findById")
    public String findById(@RequestParam("payId") Long payId, Model model) {
        // 根据ID查询支付信息
        Pay pay = payService.findById(payId);
        if (pay == null) {
            pay = new Pay();
            // 修改为正确的方法名setPayid
            pay.setPayid(payId);
        }
        model.addAttribute("pay", pay);
        return "backend/pay/edit";
    }

    // 显示支付确认页面
    @GetMapping("/confirmPay")
    public String confirmPay(@RequestParam("payId") Long payId, Model model, HttpSession session) {
        // 查询支付记录
        Pay pay = payService.findById(payId);
        if (pay == null) {
            model.addAttribute("error", "支付记录不存在");
            return "redirect:find"; // 如果支付记录不存在，重定向到列表页
        }

        // 检查支付状态是否为待支付
        if (pay.getPaystatus() != 0) {
            model.addAttribute("error", "该订单已支付或已退款，无需重复支付");
            return "redirect:find"; // 如果不是待支付状态，重定向到列表页
        }
        
        // 从session中获取当前登录用户信息
        User loginUser = (User) session.getAttribute("loginAdmin");
        
        // 只有病人用户(type=1)才能进行支付操作
        if (loginUser == null || loginUser.getType() != 1) {
            model.addAttribute("error", "您没有权限进行支付操作");
            return "redirect:find"; // 如果不是病人用户，重定向到列表页
        }

        model.addAttribute("pay", pay);
        return "backend/pay/pay-dialog";
    }

    // 修改支付信息
    @PostMapping("/modify")
    public String modify(Pay pay, Model model) {
        try {
            payService.modify(pay);
            return "redirect:find";
        } catch (Exception e) {
            model.addAttribute("error", "修改失败: " + e.getMessage());
            model.addAttribute("pay", pay);
            return "backend/pay/edit";
        }
    }

    // 后台支付处理
    @PostMapping("/payRecord")
    public String payRecord(@RequestParam("payId") Long payId,
                            @RequestParam("payMethod") String payMethod,
                            Model model, HttpSession session) {
        try {
            // 从session中获取当前登录用户信息
            User loginUser = (User) session.getAttribute("loginAdmin");
            
            // 只有病人用户(type=1)才能进行支付操作
            if (loginUser == null || loginUser.getType() != 1) {
                model.addAttribute("error", "您没有权限进行支付操作");
                return "redirect:find"; // 如果不是病人用户，重定向到列表页
            }
            
            // 查询支付记录
            Pay pay = payService.findById(payId);
            if (pay == null) {
                model.addAttribute("error", "支付记录不存在");
                return "redirect:find";
            }

            // 获取当前时间作为支付时间
            LocalDateTime now = LocalDateTime.now();
            String payTimeStr = now.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            // 更新支付状态
            pay.setPayMethod(payMethod);
            pay.setPayStatus(1); // 已支付
            pay.setPayTime(payTimeStr);

            // 如果没有订单号，生成一个
            if (pay.getOrderNo() == null || pay.getOrderNo().isEmpty()) {
                String orderNo = "PAY" + System.currentTimeMillis();
                pay.setOrderNo(orderNo);
            }

            // 更新支付记录
            payService.modify(pay);
            
            // 重新查询支付记录，确保数据已更新
            Pay updatedPay = payService.findById(payId);
            System.out.println("更新后的支付记录: " + updatedPay);
            System.out.println("更新后pay.appointmentid: " + updatedPay.getAppointmentid());
            System.out.println("更新后pay.paystatus: " + updatedPay.getPaystatus());

            // 设置会话属性，用于支付成功提示
            session.setAttribute("success", "支付成功");
            session.setAttribute("payTime", payTimeStr);
            
            // 支付成功后，创建报告记录
            Long appointmentId = updatedPay.getAppointmentid(); // 使用更新后的支付记录获取预约ID
            System.out.println("支付成功，appointmentId: " + appointmentId);
            
            if (appointmentId != null) {
                Appointment appointment = appointmentService.findById(appointmentId);
                System.out.println("查询到的appointment: " + appointment);
                
                if (appointment != null) {
                    Long userId = appointment.getUserid();
                    System.out.println("查询到的userId: " + userId);
                    
                    if (userId != null) {
                        try {
                            // 创建报告对象
                            Report report = new Report();
                            report.setUserid(userId);
                            report.setAppointmentid(appointmentId);
                            
                            // 设置症状信息，优先从appointment中获取
                            if (appointment.getSymptoms() != null && !appointment.getSymptoms().isEmpty()) {
                                report.setSymptoms(appointment.getSymptoms());
                            } else {
                                report.setSymptoms("患者已支付，等待就诊。");
                            }
                            
                            report.setDoctoradvice("待医生诊断后更新");
                            report.setCreatetime(LocalDateTime.now());
                            report.setCreateTime(report.getCreatetime().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                            
                            System.out.println("准备保存报告记录: " + report);
                            
                            // 验证必要字段
                            if (report.getUserid() == null || report.getAppointmentid() == null) {
                                throw new IllegalArgumentException("报告记录缺少必要字段: userid=" + report.getUserid() + ", appointmentid=" + report.getAppointmentid());
                            }
                            
                            // 保存报告记录
                            reportService.add(report);
                            
                            // 验证报告是否成功保存
                            Report savedReport = reportService.findById(report.getReportid());
                            if (savedReport != null) {
                                System.out.println("报告记录保存成功，reportid: " + report.getReportid());
                                System.out.println("保存的报告记录内容: userid=" + report.getUserid() + ", appointmentid=" + report.getAppointmentid() + ", symptoms=" + report.getSymptoms());
                            } else {
                                System.out.println("警告: 报告记录已保存但无法查询到，可能存在数据问题");
                            }
                        } catch (Exception e) {
                            // 记录异常但不影响支付流程
                            System.err.println("创建报告记录失败: " + e.getMessage());
                            e.printStackTrace();
                            // 打印完整的异常堆栈信息
                            StringWriter sw = new StringWriter();
                            PrintWriter pw = new PrintWriter(sw);
                            e.printStackTrace(pw);
                            System.err.println("详细异常信息: " + sw.toString());
                        }
                    } else {
                        System.out.println("userId为null，无法创建报告");
                    }
                } else {
                    System.out.println("未查询到预约信息，无法创建报告");
                }
            } else {
                System.out.println("appointmentId为null，无法创建报告");
            }

            return "redirect:find";
        } catch (Exception e) {
            model.addAttribute("error", "支付失败: " + e.getMessage());
            return "redirect:find";
        }
    }

    // 删除支付（保留原有功能）
    @GetMapping("/removeById")
    public String removeById(@RequestParam("payId") Long payId) {
        // 临时修改以触发重新解析
        payService.removeById(payId);
        return "redirect:find";
    }
}
